<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus';
import { ref } from 'vue';

interface RuleForm {
  username: string
  password: string
  rememberme: boolean
}

const ruleFormRef = ref()
const ruleForm = ref<RuleForm>({
  username: '',
  password: '',
  rememberme: true
})

const rules = ref<FormRules<RuleForm>>({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 6, max: 10, message: '用户名长度在6-10之间', trigger: ['blur', 'change'] },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9]{8}$/, message: '请输入8位密码', trigger: ['blur', 'change'] }
  ]
})

const login = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('submit!')
    } else {
      console.log('error submit!', fields)
    }
  })
}

const reset = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>

<template>
  <div class="home">
    <div class="form-login">
      <h2 class="title">智慧园区-登录</h2>
      <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules">
        <el-form-item label="账号" prop="username">
          <el-input v-model="ruleForm.username" placeholder="请输入账号" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="ruleForm.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item prop="rememberme">
          <el-checkbox v-model="ruleForm.rememberme" label="记住我" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="login(ruleFormRef)">登录</el-button>
          <el-button type="danger" @click="reset(ruleFormRef)">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<style scoped lang="scss">
.form-login {
  width: 600px;
  max-height: 600px;
  box-shadow: 0 0 10px gray;
  margin: 100px auto;
  padding: 50px;

  .title {
    text-align: center;
    margin-bottom: 20px;
  }
}
</style>
